package com.zrc.superframe_base.mvx.mvvm

import android.os.Bundle
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.zrc.superframe_base.mvx.base.BaseActivity
import com.zrc.superframe_net.interfac.NetBase
import com.zrc.superframe_ui.stateview.MultiStateContainer
import com.zrc.superframe_ui.stateview.MultiStatePage
import io.reactivex.disposables.Disposable

/**
 * @Author: superman
 * @CreateTime: 6/27/21
 * @Describe:
 */
abstract class BaseMvvmActivity<V : ViewDataBinding, M : BaseViewModel> : BaseActivity(), NetBase {
    lateinit var multiStateContainer: MultiStateContainer

    private var requestQueue= ArrayList<Disposable>() //请求队列（界面销毁时需要回收的）

    protected lateinit var mBinding: V

    protected lateinit var mViewModel: M

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this, getLayoutId())
        multiStateContainer = MultiStatePage.bindMultiState(this)
        mViewModel = ViewModelProviders.of(this, object : ViewModelProvider.Factory {
            @Suppress("UNCHECKED_CAST")
            override fun <T : ViewModel> create(modelClass: Class<T>): T {
                return getViewModel() as T
            }
        })[getViewModel().javaClass]
        mBinding.setVariable(getVariableId(), mViewModel)
        mViewModel.attach(savedInstanceState)
        mBinding.lifecycleOwner = this
        initView()
        initObserver()
        initData()
    }

    @LayoutRes
    abstract fun getLayoutId(): Int

    open fun initObserver() {

    }

    open fun initView() {}

    open fun initData() {}

    abstract fun getVariableId(): Int

    abstract fun getViewModel(): M

    override fun onDestroy() {
        super.onDestroy()
        netGc()
    }

    override fun addRequestQueue(d: Disposable)=if (requestQueue .contains(d)) {
        requestQueue.remove(d)
        false
    }else{
        requestQueue.add(d)
        true
    }

    override fun removeRequestQueue(d: Disposable) {
        requestQueue.remove(d)
    }

    override fun netGc() {
        requestQueue.forEach { //取消队列
            if (!it.isDisposed) {
                it.dispose()
            }
        }
        requestQueue.clear()
    }
}
